package com.multi.tenant.util;

import com.multi.common.constant.CacheConstants;
import com.multi.common.constant.Constants;
import com.multi.common.constant.SourceConstant;
import com.multi.common.core.domain.model.LoginUser;
import com.multi.common.core.redis.RedisCache;
import com.multi.common.exception.base.BaseException;
import com.multi.common.utils.StringUtils;
import com.multi.publicly.domain.WxUserInfo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @Description
 * @ClassName TokenUtils
 * @Author pzj
 * @Data 2024/11/11 16:41
 */
@Component
public class TokenUtils {

    @Autowired
    private RedisCache redisCache;

    /**
     *
     */
    @Value("${token.header}")
    private String header;

    // 令牌秘钥
    @Value("${token.secret}")
    private String secret;


    // 令牌有效期（默认30分钟）
    @Value("${token.expireTime}")
    private int expireTime;

    /**
     * 获取请求token
     *
     * @param request
     * @return token
     */
    public String getToken(HttpServletRequest request) {
        String token = request.getHeader(header);
        if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX)) {
            token = token.replace(Constants.TOKEN_PREFIX, "");
        }
        return token;
    }

    /**
     * 从数据声明生成令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    public String createToken(Map<String, Object> claims) {
        String token = Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, secret).compact();
        return token;
    }

    /**
     * 根据HttpServletRequest 获取用户信息
     *
     * @param request
     * @return
     */
    public WxUserInfo getWxUserInfo(HttpServletRequest request) {
        // 获取请求携带的令牌
        String token = getToken(request);
        Long userId=null;
        if (StringUtils.isNotEmpty(token)) {
            Claims claims = parseToken(token);
            // 解析对应的权限以及用户信息
            Integer uuid = (Integer) claims.get(SourceConstant.USER_ID);
            WxUserInfo user = redisCache.getCacheObject(CacheConstants.WX_USER_INFO + uuid);
            userId=new Long(uuid);
            return user;
        }
        return new WxUserInfo().setId(userId);
    }

    public String getTenantId(HttpServletRequest request){
        String token = getToken(request);
        if(StringUtils.isNotEmpty(token)){
            Claims claims = parseToken(token);
            //解析获取租户ID
            String tenantId = String.valueOf(claims.get(SourceConstant.TENANT_ID));
            return tenantId;
        }
        throw new BaseException("该租户已被禁用");
    }


    private Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }
}
